package hip.util.poi;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

@Slf4j
public class FileDownloadUtil {

    /**
     * 下载
     */
    public static void download(HttpServletRequest request, HttpServletResponse response, String contentType, String fileName, String downLoadPath) throws Exception {
        download(request, response, contentType, fileName, Files.newInputStream(Paths.get(downLoadPath)));
    }

    public static void download(HttpServletRequest request, HttpServletResponse response, String contentType, String fileName, InputStream stream) throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            String userAgent = request.getHeader("User-Agent");
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1");
            }

            response.setContentType(contentType);
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);//
            response.setHeader("Content-Length", String.valueOf(stream.available()));
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            bis = new BufferedInputStream(stream);
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }

            bis.close();
            bos.close();
        } catch (Exception e) {
            log.error("文件下载异常", e);
        } finally {
            if (bis != null) bis.close();
            if (bos != null) bos.close();
        }

    }
}